{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "40de9b92-33ad-41d1-8e40-9ab269b6883e",
   "metadata": {},
   "outputs": [],
   "source": [
    "from operator import itemgetter\n",
    "\n",
    "from langchain.memory import ConversationBufferMemory\n",
    "from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder\n",
    "from langchain_core.runnables import RunnableLambda, RunnablePassthrough\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "model = ChatOpenAI()\n",
    "prompt = ChatPromptTemplate.from_messages(\n",
    "    [\n",
    "        (\"system\", \"你是一个乐于助人的机器人\"),\n",
    "        MessagesPlaceholder(variable_name=\"history\"),\n",
    "        (\"human\", \"{input}\"),\n",
    "    ]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b07aae0c-9eaf-4d56-b4d7-da19c1c3d30a",
   "metadata": {},
   "outputs": [],
   "source": [
    "memory = ConversationBufferMemory(return_messages=True)\n",
    "memory.load_memory_variables({})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ebe69832-578f-42f7-b28d-c53da5e494fa",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 增加一条链\n",
    "chain = (\n",
    "    RunnablePassthrough.assign(\n",
    "        history=RunnableLambda(memory.load_memory_variables) | itemgetter(\"history\")\n",
    "    )\n",
    "    | prompt\n",
    "    | model\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5b13dadc-d2f4-41d8-af22-7b8b0638a228",
   "metadata": {},
   "outputs": [],
   "source": [
    "inputs = {\"input\": \"你好我是tomie\"}\n",
    "response = chain.invoke(inputs)\n",
    "response"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8f779cae-51f1-470e-aec7-6ae716879764",
   "metadata": {},
   "outputs": [],
   "source": [
    "#保存记忆\n",
    "memory.save_context(inputs, {\"output\": response.content})\n",
    "memory.load_memory_variables({})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "82a70db0-ba77-43c1-a1c8-705f0e889b62",
   "metadata": {},
   "outputs": [],
   "source": [
    "inputs = {\"input\": \"我叫什么名字?\"}\n",
    "response = chain.invoke(inputs)\n",
    "response"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f05c1951-9646-4ba3-958e-af770f6d6f5e",
   "metadata": {},
   "source": [
    "## 使用Redis来实现长时记忆"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9b10ad59-c6cf-4663-91c5-7aed593864fe",
   "metadata": {},
   "outputs": [],
   "source": [
    "! pip install redis"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7ce73833-04bd-42ac-873f-75d3140a77c2",
   "metadata": {},
   "outputs": [],
   "source": [
    "chain_with_history = RunnableWithMessageHistory(\n",
    "    chain,\n",
    "    #使用redis存储聊天记录\n",
    "    lambda session_id: RedisChatMessageHistory(session_id, url=\"redis://localhost:6379/0\"),\n",
    "    input_messages_key=\"question\",\n",
    "    history_messages_key=\"history\",\n",
    ")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python (langchain)",
   "language": "python",
   "name": "langchain-env"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
